//
//  NFCScanViewController.swift
//  AESOLAR_IOS
//
//  Created by Mr.Wang on 2019/11/25.
//  Copyright © 2019 Mr.Wang. All rights reserved.
//

import UIKit

/// 扫码成功 输入条形码成功后进入这个页面
class NFCScanViewController: BaseUIViewController {
    
    typealias SuccessClosure = (String) -> ()
    var scanComplete: SuccessClosure?
    
    let nfcUnit = NFCUint()
    
    let barcode: String
    let longitude: String?
    let latitude: String?
    let address: String?
    
    init(barcode: String, longitude: String?, latitude: String?, address: String?) {
        self.barcode = barcode
        self.longitude = longitude
        self.latitude = latitude
        self.address = address
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupView()
        
        nfcUnit.timeOutClosuer = { [weak self] in
            self?.navigationController?
                .pushTo(FailureViewController(psrCheckId: "", barCode: self?.barcode ?? "", errorMessage: "该产品未录入我司系统，请按提示完成报假程序".localized, errorCode: "50015"), remove: 1)
        }
        
        nfcUnit.nfcErrorClosure = { [weak self] error in
            let alert = UIAlertController.init(title: "系统提示".localized, message: error, preferredStyle: .alert)
            alert.addAction(UIAlertAction.init(title: "确定".localized, style: .cancel, handler: { _ in
            }))
            self?.present(alert, animated: true, completion: nil)
        }
        
        nfcUnit.successClosure = { [weak self] udid in
            self?.check(UDID: udid)
        }
    }
    
    func setupView() {
        self.view.backgroundColor = .white
        self.navigationItem.title = "江苏新源".localized
        
        let imageView = UIImageView().config
            .contentMode(.scaleToFill)
            .addTo(view)
            .makeConstraints { (make) in
                make.left.right.equalToSuperview()
                make.top.equalTo(10)
                make.height.equalTo(SCREEN_WIDTH * 0.693)
        }.view
        
        if let path = Bundle.main.path(forResource: "nfc.gif", ofType: nil),
            let data = try? Data.init(contentsOf: URL.init(fileURLWithPath: path)) {
            imageView.image = UIImage.sd_tz_animatedGIF(with: data)
        }
       
        let tipLabel = UILabel().config
            .text("请将手机背面贴近芯片标签".localized)
            .textAlignment(.center)
            .font(UIFont.systemFont(ofSize: 16, weight: .medium))
            .textColor(APPConfig.baseColor)
            .numberOfLines(0)
            .addTo(view)
            .makeConstraints { (make) in
                make.centerX.equalToSuperview()
                make.top.equalTo(imageView.snp.bottom)
                make.left.equalTo(20)
        }.view
        
        UIButton().config
            .backgroundImage(UIImage.imageWithColor(APPConfig.baseColor))
            .title("识别芯片".localized)
            .cornerRadius(22)
            .clipsToBounds(true)
            .titleColor(.white)
            .addTarget(self, action: #selector(scan))
            .addTo(view)
            .makeConstraints { (make) in
                make.centerX.equalToSuperview()
                make.width.equalTo(180)
                make.height.equalTo(44)
                make.top.equalTo(tipLabel.snp.bottom).offset(50)
        }
    }
    
    func check(UDID: String) {
        ApiManager.verify(UDID, barcode: barcode, longitude: longitude ?? "", latitude: latitude ?? "", address: address ?? "").request()
            .errorWhenCodeNot200()
            .dataModelMap(CheckModel.self)
            .trackingLoading()
            .subscribe(onNext: { [weak self] (result) in
                if result.result.isSuccess {
                    if let scanComplete = self?.scanComplete {
                        scanComplete(result.psrInfo.barcode)
                        self?.navigationController?.popViewController(animated: true)
                    } else {
                        self?.navigationController?.pushTo(SuccessViewController(result: result.psrInfo), remove: 1)
                    }
                } else {
                    self?.navigationController?
                        .pushTo(FailureViewController(psrCheckId: result.id, barCode: result.barcode, errorMessage: result.checkMsg, errorCode: result.code), remove: 1)
                }}).disposed(by: rx.disposeBag)
    }
    
    @objc func scan() {
        nfcUnit.beginScan()
    }
    
    override func navigationBarStyle() -> NavigationBarStyle {
        return .baseColor
    }
}
